package com.zxy.leetcode.lcof;

import com.zxy.leetcode.common.ListNode;
import com.zxy.leetcode.common.ListNodeHelper;

/**
 * https://leetcode-cn.com/problems/shan-chu-lian-biao-de-jie-dian-lcof/
 *
 * 删除链表的节点
 * 给定单向链表的头指针和一个要删除的节点的值，定义一个函数删除该节点。
 * 返回删除后的链表的头节点。
 *
 * 标签：链表
 */
public class Test18 {

    public static void main(String[] args) {
        Test18 test = new Test18();
        ListNode head = ListNodeHelper.build(10);
        ListNodeHelper.print(head);
        test.deleteNode(head, 4);
        ListNodeHelper.print(head);
        test.deleteNode(head, 12);
        ListNodeHelper.print(head);
    }

    public ListNode deleteNode(ListNode head, int val) {
        if (head == null) {
            return null;
        }

        if (head.val == val) {
            return head.next;
        }

        ListNode pre = head;
        ListNode node = pre.next;
        while (node != null) {
            if (node.val == val) {
                pre.next = node.next;
            }
            pre = node;
            node = node.next;
        }
        return head;
    }

}
